<template>
  <el-card>
    <!-- 单据编号放在右上角 -->
    <template #header>
      <div class="card-header">
        <h1 class="title-center">采购单</h1>
        <span class="document-number">单据编号：<u>{{ form.yclcg_code }}</u></span>
      </div>
    </template>

    <el-form :model="form" label-width="120px" ref="formRef" :rules="rules">
      <!-- 入库仓库、供应商、经手人、业务日期放在一行 -->
      <el-row :gutter="20">
        <el-col :span="6">
          <el-form-item label="入库仓库*" prop="warehouse_name">
            <el-select v-model="form.warehouse_name" placeholder="请选择所属仓库" disabled>
              <el-option v-for="option in warehouseOptions" :key="option.value" :label="option.label"
                :value="option.value" />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="供应商" prop="supplier_name">
            <el-select v-model="form.supplier_name" placeholder="请选择供应商名称/编码" disabled>
              <el-option v-for="option in gysOptions" :key="option.value" :label="option.label" :value="option.value" />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="经手人" prop="yclcg_ry">
            <el-select v-model="form.yclcg_ry" placeholder="请选择" disabled>
              <el-option v-for="option in jsrOptions" :key="option.value" :label="option.label" :value="option.value" />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="业务日期" prop="yclcg_time">
            <el-date-picker v-model="form.yclcg_time" type="date" placeholder="请选择日期" disabled />
          </el-form-item>
        </el-col>
      </el-row>

      <!-- 表格部分 -->
      <el-table :data="cgxqData" style="width: 100%; margin-bottom: 20px;" border>
        <!-- 表格列定义 -->
        <el-table-column label="序号" type="index" width="80" align="center" />
        <el-table-column label="物料编码" align="center" prop="wl_code">
          <template #default="{ row }">
            <span>{{ row.wl_code }}</span>
          </template>
        </el-table-column>
        <el-table-column label="物料名称" align="center" prop="wl_name">
          <template #default="{ row }">
            <span>{{ row.wl_name }}</span>
          </template>
        </el-table-column>
        <el-table-column label="数量" align="center" prop="yclcg_sl">
          <template #default="{ row }">
            <el-input v-model="row.yclcg_sl" @change="updateXj(row)" />
          </template>
        </el-table-column>
        <el-table-column label="单位" align="center" prop="yclcg_dw">
          <template #default="{ row }">
            <span>{{ row.yclcg_dw }}</span>
          </template>
        </el-table-column>
        <el-table-column label="单价（元）" align="center" prop="yclcg_dj">
          <template #default="{ row }">
            <span>{{ row.yclcg_dj }}</span>
          </template>
        </el-table-column>
        <el-table-column label="小计（元）" align="center" prop="yclcg_xj">
          <template #default="{ row }">
            <span>{{ row.yclcg_xj }}</span>
          </template>
        </el-table-column>
        <el-table-column label="备注" width="200" align="center" prop="bz">
          <template #default="{ row }">
            <el-input v-model="row.bz" @change="updateBz(row)" />
          </template>
        </el-table-column>

        <!-- 合计行 -->
        <template #append>
          <div style="display: flex; justify-content: flex-end; padding: 8px; background: #f5f7fa;">
            <span style="font-weight: bold; margin-right: 20px;">合计：</span>
            <span style="font-weight: bold;">{{ calculateTotal() }} 元</span>
          </div>
        </template>
      </el-table>

      <!-- 折扣率、折扣金额、附加金额、结算方式 -->
      <el-row :gutter="20">
        <el-col :span="6">
          <el-form-item label="折扣率%" prop="yclcg_zkl">
            <el-input v-model="form.yclcg_zkl" type="number" @change="calculateDiscount" />
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="折扣金额（元）" prop="yclcg_zkje">
            <el-input v-model="form.yclcg_zkje" type="number" disabled />
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="附加金额（元）" prop="yclcg_fjje">
            <el-input v-model="form.yclcg_fjje" type="number" @change="calculateReceivedAmount" />
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="结算方式" prop="yclcg_jsfs">
            <el-select v-model="form.yclcg_jsfs" placeholder="请选择">
              <el-option label="现金" value="cash" />
              <el-option label="信用卡" value="creditCard" />
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>

      <!-- 单据备注 -->
      <el-form-item label="单据备注" prop="djbz">
        <el-input v-model="form.djbz" type="textarea" />
      </el-form-item>

      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="总计金额">
            <el-input v-model="form.yclcg_zje" disabled />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="实收金额">
            <el-input v-model="form.yclcg_ssje" disabled />
          </el-form-item>
        </el-col>
      </el-row>

      <!-- 操作按钮 -->
      <el-form-item>
        <el-button @click="onCancel">取消</el-button>
        <el-button type="primary" @click="onSubmit">保存</el-button>

      </el-form-item>
    </el-form>
  </el-card>
</template>

<script>
import { ref, reactive, onMounted, nextTick } from 'vue';
import { useRoute, useRouter } from 'vue-router';
import axios from 'axios';
import { ElMessage, ElMessageBox } from 'element-plus';

export default {
  setup() {
    const route = useRoute();
    const router = useRouter(); // 使用 useRouter
    const formRef = ref(null);
    const warehouseOptions = ref([]);
    const gysOptions = ref([]);
    const jsrOptions = ref([]);

    const form = reactive({
      yclcg_id: '',
      yclcg_code: '',
      yclcg_ry: '',
      yclcg_time: '',
      yclcg_zkl: '',
      yclcg_zkje: '',
      yclcg_fjje: '',
      yclcg_jsfs: '',
      djbz: '',
      yclcg_zje: '',
      yclcg_ssje: '',
      yclcg_djzt: '',
      warehouse_name: '',
      supplier_name: '',
      dhcode: '',
      dhzt: ''
    });

    const cgxqData = ref([]);
 
    // 初始化数据
    onMounted(async () => {
      fetchjsrOptions();
  // 获取传递过来的 yclcg_code
  const yclcg_code = route.query.yclcg_code;

  // 根据 yclcg_code 查询数据主表
  const cgResponse = await axios.get(`api/Rm_yclcg/Getcg?code=${yclcg_code}`);
  const cg1 = cgResponse.data;

  // 根据 yclcg_code 查询数据子表
  const cgxqResponse = await axios.get(`api/Rm_yclcgxq/Getcgxq?code=${yclcg_code}`);
  const cgxq1 = cgxqResponse.data;

  // 将查询到的数据赋值给表单和表格
  Object.assign(form, cg1);

  // 确保 cgxq1 是一个数组
  if (Array.isArray(cgxq1)) {
    cgxqData.value = cgxq1;
  } else if (typeof cgxq1 === 'object' && cgxq1 !== null) {
    // 如果 cgxq1 是一个对象，将其转换为数组
    cgxqData.value = [cgxq1];
  } else {
    // 如果 cgxq1 是其他类型，初始化为空数组
    cgxqData.value = [];
  }

  // 确保数据在表格渲染之前赋值
  nextTick(() => {
    console.log('Table data updated:', cgxqData.value);
  });
});
    const fetchjsrOptions = async () => {
      jsrOptions.value = [
        { label: '张三', value: '1' },
        { label: '李四', value: '2' },
        { label: '王五', value: '3' },
        { label: '赵六', value: '4' },
      ]
    }
    const updateBz = (row) => {
  console.log('备注更新:', row.bz);
  // 这里可以添加其他业务逻辑，比如验证备注内容等
};

    // 更新小计
    const updateXj = (row) => {
      if (row.yclcg_dj && row.yclcg_sl) {
        row.yclcg_xj = (parseFloat(row.yclcg_dj) * parseFloat(row.yclcg_sl)).toFixed(2);
      } else {
        row.yclcg_xj = 0;
      }
    };

    // 计算合计金额
    const calculateTotal = () => {
      if (!Array.isArray(cgxqData.value) || cgxqData.value.length === 0) {
        return 0;
      }
      return cgxqData.value.reduce((total, item) => {
        const xj = parseFloat(item.yclcg_xj) || 0;
        return total + xj;
      }, 0);
    };

    // 计算折扣金额
    const calculateDiscount = () => {
      const totalAmount = calculateTotal();
      const discountRate = parseFloat(form.yclcg_zkl) || 0;

      if (isNaN(discountRate)) {
        form.yclcg_zkje = 0;
      } else {
        form.yclcg_zkje = (totalAmount - (totalAmount * (discountRate / 100))).toFixed(2);
      }

      // 更新总计金额
      form.yclcg_zje = (totalAmount - parseFloat(form.yclcg_zkje)).toFixed(2);
      // 更新实收金额
      calculateReceivedAmount();
    };

    // 计算实收金额
    const calculateReceivedAmount = () => {
      const totalAmount = parseFloat(form.yclcg_zje) || 0;
      const fj = parseFloat(form.yclcg_fjje) || 0;

      form.yclcg_ssje = (totalAmount + fj).toFixed(2);
    };

    // 提交审核
    const onSubmit = async () => {
      console.log('保存');
      console.log('form:', form);
      console.log('cgxqData:', cgxqData.value);
      console.log('cgxqData:', cgxqData.value[0].yclcg_code);
      const response = await axios.put('/api/Rm_yclcg/Upcgsh', {
        yclcg_code: form.yclcg_code,
        yclcg_zkje: form.yclcg_zkje,
        yclcg_zkl: form.yclcg_zkl,
        yclcg_fjje: form.yclcg_fjje,
        yclcg_jsfs: form.yclcg_jsfs,
        djbz: form.djbz,
        yclcg_zje: form.yclcg_zje,
        yclcg_ssje: form.yclcg_ssje,
        yclcg_sl: cgxqData.value[0].yclcg_sl,
      });
      console.log(response.data);

      const response2 = await axios.put('/api/Rm_yclcgxq/Upcgxxsh',{
        yclcg_code: form.yclcg_code,
        yclcg_sl: cgxqData.value[0].yclcg_sl,
        yclcg_xj: cgxqData.value[0].yclcg_xj,
        bz: cgxqData.value[0].bz,
      });
      console.log(response2.data);
       ElMessage.success('修改成功');
      router.push({ path: '/RawMaterialProcurement' });
    };



    // 取消
    const onCancel = () => {
      console.log('取消');
      router.push({ path: '/RawMaterialProcurement' });
    };

    return {
      form,
      cgxqData,
      warehouseOptions,
      gysOptions,
      jsrOptions,
      calculateTotal,
      onSubmit,
      onCancel,
      updateXj,
      calculateDiscount,
      calculateReceivedAmount,
      fetchjsrOptions,
      updateBz
    };
  }
}
</script>

<style scoped>
.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.title-center {
  text-align: center;
  flex: 1;
  /* 让标题占据剩余空间，使其居中 */
}

.document-number {
  font-size: 14px;
  color: #666;
}

.el-table {
  margin-bottom: 20px;
  /* 表格与下方内容隔开 */
}

.el-table--border {
  border: 1px solid #ebeef5;
}

.el-table--border th,
.el-table--border td {
  border-right: 1px solid #ebeef5;
  border-bottom: 1px solid #ebeef5;
}
</style>